import {
  _decorator,
  Component,
  Node,
  Vec3,
  UITransform,
  EventTouch,
  instantiate,
  Prefab,
} from "cc";
import { Cell } from "./Cell";
import { GameManager } from "./GameManager";
import {  CellGroupConfig } from "./Types";
import { GestureRecognizer } from "./utils/GestureRecognizer";
const { ccclass, property } = _decorator;

@ccclass("CellGroup")
export class CellGroup extends Component {
  private isDragging: boolean = false;
  private rotation: number = 0;
  private originalPosition: Vec3 = null;
  private id: number;
  private cells: Cell[] = [];
  private isPickedUp: boolean = false;
  private mouseOffset: Vec3 = new Vec3();
  private lastMousePos: Vec3 = new Vec3();
  private originalRotation: number = 0;
  private gestureRecognizer: GestureRecognizer = null;
  private originalScale: Vec3 = new Vec3();
  private cellPrefab: Prefab = null;

  onLoad() {
    this.originalPosition = this.node.position.clone();
    this.gestureRecognizer = new GestureRecognizer();

    // 将所有触摸事件都绑定到节点上
    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
    this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
    this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
  }

  onDestroy() {
    if (this.node) {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    if (this.isPickedUp) {
        GameManager.instance.setPickedCellGroup(null);
    }
  }

  init(config: CellGroupConfig, cellPrefab: Prefab) {
    this.id = config.id;
    this.cellPrefab = cellPrefab;
    
    config.cells.forEach((cellData, index) => {
      const cellNode = instantiate(this.cellPrefab);
      const cell = cellNode.getComponent(Cell);

      cellNode.setPosition(0, index * -128 + 64);
      this.node.addChild(cellNode);
      this.cells.push(cell);

      this.scheduleOnce(() => {
        // 直接使用新的 exits 格式
        const exits = [
          cellData.exits.up,
          cellData.exits.right, 
          cellData.exits.down,
          cellData.exits.left
        ];
        
        cell.setExits(exits);
        cell.setType(cellData.type);
      }, 0);
    });
  }

  // 获取组内所有 Cell 的类型和出口信息
  getCellsData() {
    return this.cells.map((cell) => ({
      type: cell.getType(),
      exits: cell.getExits(),
    }));
  }

  rotate() {
    this.rotation = (this.rotation + 90) % 360;
    this.node.angle = this.rotation;
  }

  private onTouchStart(event: EventTouch) {
    const touchPos = event.getUILocation();
    this.gestureRecognizer.touchStart(touchPos);

    // 记录触摸位置，用于后续移动判断
    const canvas = this.node.parent;
    const canvasTransform = canvas.getComponent(UITransform);
    const localPos = new Vec3();
    canvasTransform.convertToNodeSpaceAR(
        new Vec3(touchPos.x, touchPos.y, 0),
        localPos
    );

    this.mouseOffset = new Vec3(
        this.node.position.x - localPos.x,
        this.node.position.y - localPos.y,
        0
    );
  }

  private onTouchMove(event: EventTouch) {
    const touchPos = event.getUILocation();
    
    // 计算移动距离
    const canvas = this.node.parent;
    const canvasTransform = canvas.getComponent(UITransform);
    const localPos = new Vec3();
    canvasTransform.convertToNodeSpaceAR(
        new Vec3(touchPos.x, touchPos.y, 0),
        localPos
    );

    // 如果移动距离太小，不执行选中逻辑
    const moveDistance = Vec3.distance(localPos, new Vec3(
        this.node.position.x - this.mouseOffset.x,
        this.node.position.y - this.mouseOffset.y,
        0
    ));

    // 如果还未选中，且移动距离足够大，则执行选中逻辑
    if (!this.isPickedUp && moveDistance > 5) {
        const pickedGroup = GameManager.instance.getPickedCellGroup();
        if (pickedGroup && pickedGroup !== this) {
            pickedGroup.putDown();
        }

        this.originalPosition = this.node.position.clone();
        this.originalRotation = this.rotation;
        this.originalScale.set(this.node.scale);
        
        this.isPickedUp = true;
        GameManager.instance.setPickedCellGroup(this);
        this.node.setSiblingIndex(999);
        this.node.setScale(1, 1, 1);
    }

    if (!this.isPickedUp || GameManager.instance.getPickedCellGroup() !== this) {
        return;
    }

    event.propagationStopped = true;


    this.node.position = new Vec3(
        localPos.x + this.mouseOffset.x,
        localPos.y + this.mouseOffset.y,
        0
    );
  }

  private onTouchEnd(event: EventTouch) {
    const touchPos = event.getUILocation();
    const isClick = this.gestureRecognizer.touchEnd(touchPos);

    if (isClick) {
        if (!this.isPickedUp) {
            console.log('点击未选中的组件，执行选中逻辑');
            // 点击未选中的组件，执行选中逻辑
            const pickedGroup = GameManager.instance.getPickedCellGroup();
            if (pickedGroup && pickedGroup !== this) {
                pickedGroup.putDown();
            }

            this.originalPosition = this.node.position.clone();
            this.originalRotation = this.rotation;
            this.originalScale.set(this.node.scale);
            
            this.isPickedUp = true;
            GameManager.instance.setPickedCellGroup(this);
            this.node.setSiblingIndex(999);
            this.node.setScale(1, 1, 1);
        } else {
          console.log('点击已选中的组件，执行旋转');
            // 点击已选中的组件，执行旋转
            this.rotate();
        }
        return;
    }

    // 非点击结束时的处理逻辑
    if (this.isPickedUp) {
        this.isPickedUp = false;
        GameManager.instance.setPickedCellGroup(null);
        const success = GameManager.instance.tryPlaceCellGroup(this);
        
        if (!success) {
            this.node.position = this.originalPosition;
            this.rotation = this.originalRotation;
            this.node.angle = this.originalRotation;
            this.node.scale = this.originalScale;
        }
    }

    this.gestureRecognizer.reset();
  }

  private onTouchCancel(event: EventTouch) {
    if (GameManager.instance.getPickedCellGroup() !== this) {
        return;
    }

    const touchPos = event.getUILocation();
    const isClick = this.gestureRecognizer.touchEnd(touchPos);

    if (this.isPickedUp) {
      // 如果是点击且已经被拿起，保持拿起状态
      if (isClick) {
        return;
      }

      // 如果是拖动结束，尝试放置
      this.isPickedUp = false;
      GameManager.instance.setPickedCellGroup(null);
      const success = GameManager.instance.tryPlaceCellGroup(this);
      if (!success) {
        // 放置失败，恢复位置和旋转
        this.node.position = this.originalPosition;
        this.rotation = this.originalRotation;
        this.node.angle = this.originalRotation;
        // 恢复原始缩放（如果有需要）
        this.node.scale = this.originalScale;
      }
    }

    this.gestureRecognizer.reset();
  }

  // 获取当前组在网格中的位置
  getGridPosition(): { x: number; y: number } {
    const worldPos = this.node.worldPosition;
    return GameManager.instance.worldToGrid(worldPos);
  }

  private updateCellExits(cell: Cell) {
    // 获取当前的旋转角度(0, 90, 180, 270)
    const currentRotation = this.rotation;

    // 获取cell原始的出口方向
    const originalExits = cell.getExits();
    const newExits: boolean[] = [false, false, false, false];

    // 根据旋转角度调整出口方向
    // 出口数组索引: [上(0), 右(1), 下(2), 左(3)]
    originalExits.forEach((hasExit, index) => {
      if (hasExit) {
        // 计算旋转后的新索引
        const newIndex = (index + currentRotation / 90) % 4;
        newExits[newIndex] = true;
      }
    });

    // 更新cell的出口
    cell.setExits(newExits);
  }

  // 添加 public putDown 方法
  public putDown(): void {
    if (!this.isPickedUp) return;
    
    this.isPickedUp = false;
    GameManager.instance.setPickedCellGroup(null);
    this.node.position = this.originalPosition;
    this.rotation = this.originalRotation;
    this.node.angle = this.originalRotation;
    this.node.scale = this.originalScale;
  }
}
